﻿using Demo.PetaPoco.Application;
using Demo.PetaPoco.Application.Dtos.Dept;
using Demo.PetaPoco.Application.Dtos.Vue;
using Demo.PetaPoco.Application.Extensions;
using PmSoft.FormSchema;
using Demo.PetaPoco.Application.Services.Dept;
using Microsoft.AspNetCore.Mvc;
using PmSoft.Web.Abstractions;
using PmSoft.Web.Abstractions.Attributes;

namespace Demo.PetaPoco.WebApi.Controllers.System;

[Route("api/system/[controller]")]
[ApiController]
[RestrictAccess(allowedTenantTypes: ["SysUser"])]
public class DeptController(DeptService deptService) : ControllerBase
{
	[HttpGet("list")]
	public async Task<IApiResult> GetPageListAsync([FromQuery] DeptPageQuery query)
	{
		var paged = await deptService.GetPagedListAsync(query);
		return ApiResult.Ok(paged);
	}

	[HttpGet("editFormSchema")]
	public async Task<IApiResult> GetEditFormSchemaAsync(int deptId)
	{
		var deptDetail = await deptService.GetDeptDetailAsync(deptId);
		var editModel = deptDetail.MapTo<DeptDetailDto, DeptEditModel>();
		editModel.Areas = deptDetail.ToAreas();
		var formSchema = FormSchemaGenerator.GenerateSchema(editModel);
		return ApiResult.Ok(formSchema);
	}

	[HttpGet("detail")]
	public async Task<IApiResult> GetDetailAsync(int deptId)
	{
		var detailDto = await deptService.GetDeptDetailAsync(deptId);
		return ApiResult.Ok(detailDto);
	}

	[HttpPut("update")]
	public async Task<IApiResult> UpdateAsync(DeptEditModel model)
	{
		await deptService.UpdateAsync(model);
		return ApiResult.Ok("保存成功");
	}

	[HttpPost("create")]
	public async Task<IApiResult> CreateAsync(DeptCreateModel model)
	{
		await deptService.CreateAsync(model);
		return ApiResult.Ok("创建成功");
	}

	[HttpDelete("delete")]
	public async Task<IApiResult> DeleteAsync(int deptId)
	{
		await deptService.DeleteAsync(deptId);
		return ApiResult.Ok("删除成功");
	}

	[HttpGet("select")]
	public async Task<IApiResult> SelectAsync()
	{
		var depts = await deptService.GetPagedListAsync(new DeptPageQuery { });
		return ApiResult.Ok(depts.Items.Select(m => new OptionItem { Label = m.Name, Value = m.Id }));
	}
}
